﻿using SuperSocket.SocketBase.Config;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace WinServer
{
    public partial class FormServer : Form
    {
        SortedList<string, HansAppSession> list = new SortedList<string, HansAppSession>();
        HansAppServer appServer;

        public FormServer()
        {
            InitializeComponent();
        }

        private void btnSend_Click(object sender, EventArgs e)
        {
            if (cboClientList.SelectedIndex == -1)
            {
                MessageBox.Show("请选择一个客户端对象");
                return;

            }
            if (rtxtSendMessage.Text.Length == 0)
            {
                MessageBox.Show("请输入发送内容！", "提示");

                rtxtSendMessage.Focus();
                return;

            }
            string sessionIp = cboClientList.Items[cboClientList.SelectedIndex].ToString();
            HansAppSession sessionTo = list[sessionIp];
            sessionTo.Send(rtxtSendMessage.Text);
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            HansAppServer.Encoder = Encoding.GetEncoding("gbk");

            HansAppServer.StartMark = txtStartMark.Text;

            HansAppServer.EndMark = txtEndMark.Text;

            appServer = new HansAppServer();

            ServerConfig serverConfig = new ServerConfig();

            System.Net.IPHostEntry ipHost = System.Net.Dns.GetHostEntry(System.Net.Dns.GetHostName());

            System.Net.IPAddress[] ipCollection = ipHost.AddressList;

            string ip = "";
            for (int i = 0; i < ipCollection.Length; i++)
            {
                if (ipCollection[i].AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork)
                {
                    ip = ipCollection[i].ToString();
                    break;

                }

            }

            //如果注释下一行代码，则默认编码格式为ASCII

            serverConfig.TextEncoding = HansAppServer.Encoder.BodyName;// "gbk";//gb2312

            serverConfig.Ip = ip;

            serverConfig.Port = 20188;

            if (!appServer.Setup(serverConfig))
            {

                MessageBox.Show("开启监听端口失败");
                return;

            }

            if (!appServer.Start())
            {
                MessageBox.Show("服务器开启监听失败");
                return;

            }

            appServer.NewSessionConnected -= AppServer_NewSessionConnected;

            appServer.NewRequestReceived -= AppServer_NewRequestReceived;

            appServer.SessionClosed -= AppServer_SessionClosed;

            //客户端连接事件

            appServer.NewSessionConnected += AppServer_NewSessionConnected;

            //接收事件

            appServer.NewRequestReceived += AppServer_NewRequestReceived;

            //客户端已关闭事件

            appServer.SessionClosed += AppServer_SessionClosed;

            DisplayContent(string.Format("服务器启动监听成功,服务器IP：{0},端口：{1}\r\n", appServer.Config.Ip, appServer.Config.Port));

            //MessageBox.Show("服务器启动监听成功");

        }

        private void AppServer_NewRequestReceived(HansAppSession session, HansRequestInfo requestInfo)
        {
            /// 接收来自客户端的内容，客户端发送的内容以\r\n作为结束符
            string body = session.Charset.GetString(requestInfo.Body.BodyBuffer);

            string charSet = session.Charset.BodyName;

            DateTime dt = session.LastActiveTime;

            string key = session.CurrentCommand;
            StringBuilder sb = new StringBuilder(key);

            if (body.Length > 0)
            {
                sb.Append(":" + body);

            }
            sb.Append("\r\n发送时间：" + dt.ToString("yyyy-MM-dd HH:mm:ss"));
            sb.Append(",字符编码：" + charSet);
            sb.Append("\r\n");
            DisplayContent(sb.ToString());
            //session.Send("abc123你好");
        }

        private void AppServer_SessionClosed(HansAppSession session, SuperSocket.SocketBase.CloseReason value)
        {
            //MessageBox.Show("客户端已关闭:" + value);
            string sessionIp = string.Format("{0}:{1}", session.RemoteEndPoint.Address, session.RemoteEndPoint.Port);
            list.Remove(sessionIp);
            this.Invoke(new MethodInvoker(() =>
            {
                DisplayContent(string.Format("客户端已关闭：{0},端口：{1}，原因：{2}\r\n", session.RemoteEndPoint.Address, session.RemoteEndPoint.Port, value));

                cboClientList.Items.Remove(sessionIp);

            }));           

        }

        private void AppServer_NewSessionConnected(HansAppSession session)
        {
            string sessionIp = string.Format("{0}:{1}", session.RemoteEndPoint.Address, session.RemoteEndPoint.Port);

            list.Add(sessionIp, session);
            this.Invoke(new MethodInvoker(() =>
            {

                DisplayContent(string.Format("客户端已连接：{0},端口：{1}\r\n", session.RemoteEndPoint.Address, session.RemoteEndPoint.Port));
                cboClientList.Items.Add(sessionIp);

            }));
            session.Send("Welcome");
        }

        /// 异步显示内容
        /// <param name="addContent"></param>

        public void DisplayContent(string addContent)
        {
            if (this.InvokeRequired)
            {
                Action<string> actionUpd = DisplayContentEx;

                actionUpd.BeginInvoke(addContent, null, null);

            }
            else
            {
                DisplayContentEx(addContent);
            }

        }

        public void DisplayContentEx(string addContent)
        {

            this.Invoke(new MethodInvoker(() =>
            {
                if (rtxtDisplay.TextLength >= 10240)
                {
                    rtxtDisplay.Clear();
                }
                rtxtDisplay.AppendText(addContent+"\r\n");
                rtxtDisplay.ScrollToCaret();

            }));

        }

        private void btnClear_Click(object sender, EventArgs e)
        {
            rtxtDisplay.Clear();
        }
    }
}
